"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useState, useEffect } from "react";
import { Asset, AssetHistory, Host, getAsset, getAssetHistory, getHosts, updateAsset } from "@/lib/api";
import { useRouter } from "next/navigation";
import { ArrowLeftIcon, PencilIcon, CalendarIcon, ServerIcon, InfoIcon, SaveIcon, XIcon } from "lucide-react";
import React from "react";

export default function AssetDetailPage({ params }: { params: Promise<{ asset_number: string }> }) {
  const router = useRouter();
  const [asset, setAsset] = useState<Asset | null>(null);
  const [assetHistory, setAssetHistory] = useState<AssetHistory[]>([]);
  const [hosts, setHosts] = useState<Host[]>([]);
  const [loading, setLoading] = useState(true);
  const [hostsLoading, setHostsLoading] = useState(false);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editFormData, setEditFormData] = useState({
    name: "",
    status: "idle",
    host: "" // 确保host始终是字符串类型
  });
  const [isSaving, setIsSaving] = useState(false);
  const unwrappedParams = React.use(params);

  useEffect(() => {
    const fetchAsset = async () => {
      try {
        setLoading(true);
        const data = await getAsset(unwrappedParams.asset_number);
        setAsset(data);
        setError(null);
      } catch (err) {
        setError("Failed to fetch asset");
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchAsset();
  }, [unwrappedParams.asset_number]);

  // 添加获取资产历史记录的useEffect
  useEffect(() => {
    const fetchAssetHistory = async () => {
      if (!unwrappedParams.asset_number) return;
      
      try {
        setHistoryLoading(true);
        const data = await getAssetHistory(unwrappedParams.asset_number);
        setAssetHistory(data);
      } catch (err) {
        console.error("Failed to fetch asset history", err);
      } finally {
        setHistoryLoading(false);
      }
    };

    fetchAssetHistory();
  }, [unwrappedParams.asset_number]);

  useEffect(() => {
    const fetchHosts = async () => {
      try {
        setHostsLoading(true);
        const data = await getHosts();
        setHosts(data.results);
      } catch (err) {
        console.error("Failed to fetch hosts", err);
      } finally {
        setHostsLoading(false);
      }
    };

    fetchHosts();
  }, []);

  useEffect(() => {
    if (asset) {
      setEditFormData({
        name: asset.name,
        status: asset.status,
        host: asset.host ? asset.host.toString() : "none"
      });
    }
  }, [asset]);

  const handleBack = () => {
    router.push('/assets');
  };

  const handleEdit = () => {
    setIsEditDialogOpen(true);
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setEditFormData(prev => ({
      ...prev,
      [id]: value
    }));
  };

  const handleSelectChange = (value: string, name: string) => {
    setEditFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSaveEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!asset) return;
    
    try {
      setIsSaving(true);
      const updatedAsset = await updateAsset(asset.asset_number, {
        name: editFormData.name,
        status: editFormData.status,
        host: editFormData.host && editFormData.host !== "none" ? parseInt(editFormData.host) : null
      });
      
      setAsset(updatedAsset);
      setIsEditDialogOpen(false);
    } catch (err) {
      console.error("Failed to update asset", err);
      // 可以添加一个用户友好的错误提示
      alert("Failed to update asset. Please check the console for details.");
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <div className="flex items-center space-x-4">
              <Button variant="outline" size="icon" onClick={handleBack}>
                <ArrowLeftIcon className="h-4 w-4" />
              </Button>
              <div>
                <CardTitle className="text-3xl font-bold">Asset Details</CardTitle>
                <CardDescription>Loading asset information...</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {[1, 2, 3, 4, 5].map((item) => (
                <div key={item} className="h-6 bg-gray-200 rounded animate-pulse"></div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error || !asset) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <div className="flex items-center space-x-4">
              <Button variant="outline" size="icon" onClick={handleBack}>
                <ArrowLeftIcon className="h-4 w-4" />
              </Button>
              <div>
                <CardTitle className="text-3xl font-bold">Asset Details</CardTitle>
                <CardDescription className="text-red-500">{error || "Asset not found"}</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground">Failed to load asset details. Please try again later.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Generate avatar initials from asset name
  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  if (asset) {
    return (
      <div className="container mx-auto py-10">
        <div className="flex items-center space-x-4 mb-6">
          <Button variant="outline" size="sm" onClick={() => router.push("/assets")}>
            <ArrowLeftIcon className="h-4 w-4" />
          </Button>
          <h1 className="text-3xl font-bold">Asset Details</h1>
        </div>
        
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <Avatar>
                  <AvatarFallback>{asset.name.charAt(0)}</AvatarFallback>
                </Avatar>
                <div>
                  <CardTitle className="text-2xl">{asset.name}</CardTitle>
                  <CardDescription>Asset Number: {asset.asset_number}</CardDescription>
                </div>
              </div>
              <Button onClick={handleEdit}>
                <PencilIcon className="h-4 w-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="overview" className="w-full">
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="overview">Overview</TabsTrigger>
                <TabsTrigger value="details">Details</TabsTrigger>
                <TabsTrigger value="host">Host Information</TabsTrigger>
                <TabsTrigger value="history">History</TabsTrigger>
              </TabsList>
              
              <TabsContent value="overview" className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Status</CardTitle>
                      <InfoIcon className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        <Badge variant={asset.status === "active" ? "default" : asset.status === "maintenance" ? "secondary" : "destructive"}>
                          {asset.status.charAt(0).toUpperCase() + asset.status.slice(1)}
                        </Badge>
                      </div>
                    </CardContent>
                  </Card>
                  
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Created</CardTitle>
                      <CalendarIcon className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {new Date(asset.created_time).toLocaleDateString()}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {new Date(asset.created_time).toLocaleTimeString()}
                      </p>
                    </CardContent>
                  </Card>
                  
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Host</CardTitle>
                      <ServerIcon className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {asset.host_info ? "Assigned" : "Unassigned"}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {asset.host_info ? asset.host_info.hostname : "No host"}
                      </p>
                    </CardContent>
                  </Card>
                </div>
                
                <Card>
                  <CardHeader>
                    <CardTitle>Asset Summary</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      This asset was created on {new Date(asset.created_time).toLocaleString()} and is currently 
                      {asset.status === "active" ? " active" : asset.status === "maintenance" ? " under maintenance" : " retired"}.
                      {asset.host_info ? ` It is assigned to the host ${asset.host_info.hostname}.` : " It is not assigned to any host."}
                    </p>
                  </CardContent>
                </Card>
              </TabsContent>
              
              <TabsContent value="details" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Asset Details</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-1">
                        <p className="text-sm font-medium leading-none">Name</p>
                        <p className="text-sm text-muted-foreground">{asset.name}</p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm font-medium leading-none">Asset Number</p>
                        <p className="text-sm text-muted-foreground">{asset.asset_number}</p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm font-medium leading-none">Status</p>
                        <p>
                          <Badge variant={asset.status === "active" ? "default" : asset.status === "maintenance" ? "secondary" : "destructive"}>
                            {asset.status.charAt(0).toUpperCase() + asset.status.slice(1)}
                          </Badge>
                        </p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm font-medium leading-none">Created Time</p>
                        <p className="text-sm text-muted-foreground">
                          {new Date(asset.created_time).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
              
              <TabsContent value="host" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Host Information</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {asset.host_info ? (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <p className="text-sm font-medium leading-none">Hostname</p>
                          <p className="text-sm text-muted-foreground">{asset.host_info.hostname}</p>
                        </div>
                        <div className="space-y-1">
                          <p className="text-sm font-medium leading-none">IP Address</p>
                          <p className="text-sm text-muted-foreground">{asset.host_info.ip_address}</p>
                        </div>
                        <div className="space-y-1">
                          <p className="text-sm font-medium leading-none">Location</p>
                          <p className="text-sm text-muted-foreground">
                            {"Not specified"}
                          </p>
                        </div>
                        <div className="space-y-1">
                          <p className="text-sm font-medium leading-none">Created</p>
                          <p className="text-sm text-muted-foreground">
                            {new Date(asset.host_info.created_time).toLocaleString()}
                          </p>
                        </div>
                      </div>
                    ) : (
                      <div>
                        <p className="text-muted-foreground">
                          This asset is not currently assigned to any host.
                        </p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>
              
              {/* 添加历史记录标签页 */}
              <TabsContent value="history" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Asset History</CardTitle>
                    <CardDescription>
                      View the change history for this asset
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    {historyLoading ? (
                      <div className="space-y-4">
                        {[1, 2, 3].map((item) => (
                          <div key={item} className="h-16 bg-gray-200 rounded animate-pulse"></div>
                        ))}
                      </div>
                    ) : assetHistory.length > 0 ? (
                      <div className="space-y-4">
                        {assetHistory.map((historyItem) => (
                          <div 
                            key={historyItem.id} 
                            className="border rounded-lg p-4 hover:bg-muted transition-colors"
                          >
                            <div className="flex justify-between items-start">
                              <div>
                                <h4 className="font-medium">
                                  {historyItem.field_name.charAt(0).toUpperCase() + 
                                   historyItem.field_name.slice(1)}
                                </h4>
                                <div className="flex items-center mt-1 space-x-2">
                                  <Badge variant="secondary">
                                    {historyItem.old_value || "None"}
                                  </Badge>
                                  <span className="text-muted-foreground">→</span>
                                  <Badge>
                                    {historyItem.new_value || "None"}
                                  </Badge>
                                </div>
                              </div>
                              <div className="text-right text-sm text-muted-foreground">
                                <p>
                                  {new Date(historyItem.timestamp).toLocaleDateString()}
                                </p>
                                <p>
                                  {new Date(historyItem.timestamp).toLocaleTimeString()}
                                </p>
                              </div>
                            </div>
                            {historyItem.user && (
                              <p className="text-sm text-muted-foreground mt-2">
                                Changed by: {historyItem.user}
                              </p>
                            )}
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-muted-foreground text-center py-8">
                        No history records found for this asset.
                      </p>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        {/* Edit Asset Dialog */}
        <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>Edit Asset</DialogTitle>
            </DialogHeader>
            <form onSubmit={handleSaveEdit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">Asset Name</Label>
                <Input
                  id="name"
                  value={editFormData.name}
                  onChange={handleEditInputChange}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <Select
                  value={editFormData.status}
                  onValueChange={(value) => handleSelectChange(value, "status")}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="idle">Idle</SelectItem>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="maintenance">Maintenance</SelectItem>
                    <SelectItem value="faulty">Faulty</SelectItem>
                    <SelectItem value="retired">Retired</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="host">Assigned Host</Label>
                <Select
                  value={editFormData.host}
                  onValueChange={(value) => handleSelectChange(value, "host")}
                  disabled={hostsLoading}
                >
                  <SelectTrigger>
                    <SelectValue>
                      {editFormData.host === "none" 
                        ? "No Host" 
                        : hosts.find(h => h.id.toString() === editFormData.host)?.hostname || 
                          (hostsLoading ? "Loading hosts..." : "Select a host")}
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">No Host</SelectItem>
                    {hosts.map((host) => (
                      <SelectItem key={host.id} value={host.id.toString()}>
                        {host.hostname} ({host.ip_address})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex justify-end space-x-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsEditDialogOpen(false)}
                  disabled={isSaving}
                >
                  <XIcon className="h-4 w-4" />
                  Cancel
                </Button>
                <Button type="submit" disabled={isSaving}>
                  {isSaving ? (
                    <>
                      <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                      Saving
                    </>
                  ) : (
                    <>
                      <SaveIcon className="h-4 w-4" />
                      Save Changes
                    </>
                  )}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>
      </div>
    );
  }
}
